package de.ludo.gaming;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.StreamMessage;

/**
 * Session Bean implementation class OutputRequesterBean
 */
@Stateless
@LocalBean
public class ad {

	@Resource(mappedName = "java:/JmsXA")
	private ConnectionFactory jmsFactory;

	@Resource(mappedName = "java:/queue/HighscoreQueue")
	private Queue highscoreQueue;

	private Connection jmsConnection;

	@PostConstruct
	private void startConnection() {
		try {
			jmsConnection = jmsFactory.createConnection();
			jmsConnection.start();
		} catch (JMSException e) {
			// TODO replace with output to logging framework
			e.printStackTrace();
		}
	}

	@PreDestroy
	private void closeConnection() {
		try {
			jmsConnection.close();
		} catch (JMSException e) {
			// TODO replace with output to logging framework
			e.printStackTrace();
		}
	}

	public void updateHighscore(String gametype, String username, int score) {
		Session session = null;
		try {
			session = jmsConnection.createSession(true,
					Session.SESSION_TRANSACTED);
			StreamMessage message = session.createStreamMessage();
			message.setStringProperty("gametype", gametype);
			message.setStringProperty("username", username);
			message.setIntProperty("points", score);

			// Sets message in read only mode and repositions the stream to the
			// beginning.
			// message.reset();

			MessageProducer sender = session.createProducer(highscoreQueue);
			sender.send(message);
			session.close();
		} catch (JMSException e) {
			// TODO replace with output to logging framework
			e.printStackTrace();
		}
	}

}
